import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { CfgSystemService } from './cfg-system.service';

@Component({
  selector: 'pld-cfg-system',
  templateUrl: './cfg-system.component.html',
  styleUrls: ['./cfg-system.component.less']
})
export class CfgSystemComponent implements OnInit {
  form: FormGroup = null;
  loading = false;

  constructor(
    fb: FormBuilder,
    private cfgService: CfgSystemService,
    private messageService: NzMessageService,
  ) {
    this.form = fb.group({
      title: ['', null],
      logoUrl: ['', null],
      imgHost: ['', null],
      systemHost: ['', null],
      telephone: ['', null],
    });
  }

  ngOnInit() {
    this.loadCfg();
  }

  loadCfg() {
    this.loading = true;
    this.cfgService.loadCfg().subscribe(res => {
      this.form.reset(res);
      this.loading = false;
    });
  }

  saveCfg() {
    if (this.form.valid) {
      const data = Object.assign({}, this.form.value);
      this.loading = true;
      this.cfgService.saveCfg(data).subscribe(() => {
        this.messageService.success('保存成功');
        this.loading = false;
      }, err => {
        this.messageService.success('保存失败');
      });
    } else {
      for (const controlKey of Object.keys(this.form.controls)) {
        this.form.controls[controlKey].markAsDirty();
        this.form.controls[controlKey].updateValueAndValidity();
        console.log(controlKey, this.form.controls[controlKey].errors, this.form.controls[controlKey].value);
      }
    }
  }
}
